<template>
    <view :style="objColor" id="InfoCon">
        <!-- mine/pages/set/set.wxml -->
        <form @submit="formSubmit">
        <view class="set">
            <view class="headerImgCon">
                <view>头像</view>
                <view>
                    <!-- #ifndef MP-WEIXIN -->
                    <image :src="info.icon" @click="updateImg"></image>
                    <!-- #endif -->
 
 
                    <!-- #ifdef MP-WEIXIN -->
                    <button open-type="chooseAvatar" @chooseavatar="chooseavatar" class="chooseavatar" hover-class="none">
                        <image :src="info.icon"></image>
                    </button>
                    <!-- #endif -->
 
 
                </view>
            </view>
            <view class="set-list">
                <view>昵称</view>
                
                <!-- #ifndef MP-WEIXIN -->
                <view class="listVal" @click="changName">
					<text v-if="info.name">{{info.name}}</text>
					<text class="placeholder" v-else>未填写</text>
                    <image src="https://oos-cn.ctyunapi.cn/front-end/static/mine/images/back.png"></image>
                </view>
                <!-- #endif -->
                
                <!-- #ifdef MP-WEIXIN -->
                <view class="listVal flex-row-end">
                    <input type='nickname' name='nickname' placeholder="未填写" :value='info.name' placeholder-class='placeholder'></input>
                    <image src="https://oos-cn.ctyunapi.cn/front-end/static/mine/images/back.png" style="float:none;margin:0 0 0 20rpx"></image>
                </view>
                <!-- #endif -->
                
            </view>
            <view class="set-list">
                <view>性别</view>
                <view class="listVal">
                    <picker @change="bindSexIndex" :value="info.sexIndex" :range="sexArray" range-key="name">
						<text v-if="info.sexIndex !== null">{{sexArray[info.sexIndex].name}}</text>
						<text class="placeholder" v-else>请选择</text>
                        <image src="https://oos-cn.ctyunapi.cn/front-end/static/mine/images/back.png"></image>
                    </picker>
                </view>
            </view>
            <view class="set-list">
                <view>生日</view>
                <view class="listVal">
                    <picker mode="date" :value="info.birthday" @change="bindDateChange">
						<text v-if="info.birthday">{{info.birthday}}</text>
						<text class="placeholder" v-else>请选择</text>
                        <image src="https://oos-cn.ctyunapi.cn/front-end/static/mine/images/back.png"></image>
                    </picker>
                </view>
            </view>
            <view class="set-list2">
                <view style="border-bottom: none" class="view ">所在地区</view>
                <view style="border-bottom: none" class="listVal">
                    <uni-data-picker class="listVal1" placeholder="请选择" id="pickerCon" :ellipsis='true' :step-searh="false" :preload="true"
                        :localdata="items" @change="onchange" v-model="info.areaId" @nodeclick="onnodeclick"
                        :clear-icon="false" :border="false">
							<div class="listVal1" v-if="info.areaId && province.text">{{province.text}} {{city.text}} {{area.text}}</div>
							<div v-else class="placeholder">请选择</div>
						</uni-data-picker>
                        <image class="image" src="https://oos-cn.ctyunapi.cn/front-end/static/mine/images/back.png"></image>
                </view>
            </view>
            
            
        </view>
        
        <button class="saveBtn flex-row-center" form-type="submit">保存</button>
        </form>
        <uni-popup ref="alertDialog" type="dialog">
            <uni-popup-dialog type="info" cancelText="取消" confirmText="确认" title="修改昵称" @confirm="modify"
                @close="dialogClose">
                <input class="custom_input" maxlength="16" :value="info.name" @input="changeName" />
            </uni-popup-dialog>
        </uni-popup>
 
 
    </view>
</template>
<script>
    'use strict';
    // exports.__esModule = true; // mine/pages/set/set.ts
 
    var https_1 = require('./../../../api/https.js');
    //import { area } from './../../../agreement/static/area.js'
    var app = getApp();
    export default {
 
        data() {
            return {
                type:'',
                imgUrl: app.globalData.URL,
                info: {
                    birthday: '',
                    icon: '',
                    sex: '',
                    areaId: '',
                    sexIndex:null,
                },
                time: '',
                sexArray: [{
                        name: '男',
                    },
                    {
                        name: '女',
                    }
                ],
                //items:area.areas
                items: [],
				area:{},
				city:{},
				province:{}
            };
        }
        /**
         * 生命周期函数--监听页面加载
         */
        ,
        onLoad: function(options) {
            console.log('openid',uni.getStorageSync('openId'))
            this.type = options.type
            this.getAreas()
 
        },
        /**
         * 生命周期函数--监听页面显示
         */
        onShow: function() {
 
        },
        onUnload(){
    //         if(this.type == 'login'){
				// setTimeout(()=>{
				// 	uni.reLaunch({
				// 	    url:'/pages/my/my'
				// 	})
				// })
    //         }
        },
        methods: {
            handleTreeData(data, limit = 3, count = 1) {
                return data?.map((x) => ({
                    ...x,
                    children: count < limit ? this.handleTreeData(x.children, limit, count + 1) : [],
                }))
            },
            async getAreas() {
                uni.showLoading({
                    title: '加载中...',
                    mask: true
                });
                //
 
 
                await https_1.getMemberPersonalData().then(res => {
                    if (res.code == 0) {
                        this.$nextTick(() => {
                            const {
                                icon,
                                sex,
                                name,
                                birthday,
                                areaId
                            } = res.data
                            this.info = {
                                icon,
                                sex,
                                name,
                                birthday,
                                areaId: String(areaId),
                                sexIndex:null,
                            }
							// this.info.sex = null
							if(this.info.sex!== null){
								this.info.sexIndex = this.info.sex ? 0 : 1
							}
                            
                            this.info.icon = this.info.icon.indexOf("http") != -1 ? this.info.icon :
                                'https://oos-cn.ctyunapi.cn/front-end/static/static/header-1.png'
                          
                        })
 
                    }
                })
                await https_1.getAreaTree().then(res => {
                    if (res.code == 0) {
                        this.items = this.handleTreeData(res.data)
                        // 获取选择的城市
						this.items1 = this.handleTreeData1(res.data)
						
						setTimeout(()=>{
							 this.getAddress()
						})
                       
                    }
                })
                // console.log('进入',this.info,this.items)
                uni.hideLoading()
            },
			handleTreeData1(data){
				let arr = []
				data.forEach(item=>{
					arr.push(item)
					if(item.children){
						arr.push(...this.handleTreeData1(item.children))
					}
				})
				return arr
			},
            getAddress(){
               this.area = this.getAddressItem(this.info.areaId,this.items1)
			   
			   this.city = this.getAddressItem(this.area.parentId,this.items1)
			   
			   this.province = this.getAddressItem(this.city.parentId,this.items1)
			   
            },
			getAddressItem(areaId,items,fn){
				let obj = null
				for(var i=0;i<items.length;i++){
					let item = items[i]
					if(item.value == areaId){
						return item
					}
				}
			},
            changeName: function(e) {
                this.info.name = e.detail.value
                console.log(this.info)
            },
            // 生日
            bindDateChange: function(e) {
                this.info.birthday = e.detail.value
                // this.modify()
            },
            // 性别
            bindSexIndex: function(e) {
                console.log( e.detail.value,'fdsfd',this.sexArray[e.detail.value])
                this.info.sexIndex = e.detail.value
                // this.modify()
            },
 
            dialogClose() {
                this.$refs.alertDialog.close()
            },
 
            // 上传头像
            updateImg: async function(e) {
                var that = this;
                //#ifdef APP-PLUS
					let result = await this.$store.dispatch("requestPermissions",'WRITE_EXTERNAL_STORAGE')
					if (result !== 1){
						return
					}else{
						uni.chooseImage({
						    sourceType: ['album'], //从相册选择
						    success: chooseImageRes => {
						        console.log('成功', chooseImageRes);
						        uni.showLoading({
						            title: '图片上传中...',
						            mask: true
						        });
						        const tempFilePaths = chooseImageRes.tempFilePaths;
						        uni.uploadFile({
						            url: that.imgUrl + '/member-service/common/upload', //仅为示例，非真实的接口地址
						            filePath: tempFilePaths[0],
						            name: 'file',
						            success: res => {
						                // console.log('上传成功', JSON.parse(res.data));
						                // uploadFile上传成功后，根据和后台的约定msgCode判断接口调用状态
						                let data = JSON.parse(res.data);
						                // 成功：获取到头像
						                if (data.code == 0) {
						                    this.info.icon = data.data;
						                    uni.hideLoading()
						                    // this.modify()
						                    // 更新当前页面数据
						                    //this.updateUserInfo();
						                }
						            }
						        });
						    },
						    fail: err => {
						        this.myToast('图片上传失败', 'none');
						    }
						});
					}    
				//#endif
                //#ifdef MP-WEIXIN
                	uni.chooseImage({
                	    sourceType: ['album'], //从相册选择
                	    success: chooseImageRes => {
                	        console.log('成功', chooseImageRes);
                	        uni.showLoading({
                	            title: '图片上传中...',
                	            mask: true
                	        });
                	        const tempFilePaths = chooseImageRes.tempFilePaths;
                	        uni.uploadFile({
                	            url: that.imgUrl + '/member-service/common/upload', //仅为示例，非真实的接口地址
                	            filePath: tempFilePaths[0],
                	            name: 'file',
                	            success: res => {
                	                // console.log('上传成功', JSON.parse(res.data));
                	                // uploadFile上传成功后，根据和后台的约定msgCode判断接口调用状态
                	                let data = JSON.parse(res.data);
                	                // 成功：获取到头像
                	                if (data.code == 0) {
                	                    this.info.icon = data.data;
                	                    uni.hideLoading()
                	                    // this.modify()
                	                    // 更新当前页面数据
                	                    //this.updateUserInfo();
                	                }
                	            }
                	        });
                	    },
                	    fail: err => {
                	        this.myToast('图片上传失败', 'none');
                	    }
                	});
                //#endif
            },
 
            changName: function() {
                this.$refs.alertDialog.open()
            },
            modify: function() {
                console.log(this.info)
                let data = {
                    ...this.info,
                    sex: this.info.sexIndex === null ? null : this.info.sexIndex==1?false:true
                }
                console.log(data, '===')
                https_1.updateMemberPersonalData(data).then(res => {
					if(res.code == 0){
						uni.showToast({
						    title:'保存成功',
						    icon:'none'
						})
					}else{
						uni.showToast({
						    title:res.msg || '保存异常',
						    icon:'none'
						})
					}
                    
                    console.log(res)
                })
            },
 
            onchange(e) {
                const values = e.detail.value
				
				this.area = values[2]
				
				this.city = values[1]
				
				this.province = values[0]
            },
            onnodeclick(node) {
                console.log(node)
                // this.modify()
            },
            formSubmit(e){
                console.log(e)
                this.info.name = e.detail.value.nickname || this.info.name
                this.modify()
            },
            chooseavatar(e) {
                 const tmp = this
                 let img = e.detail.avatarUrl
                uni.uploadFile({
                    url: getApp().globalData.URL + '/member-service/common/upload', // 仅为示例，非真实的接口地址
                    filePath: img,
                    name: 'file',
                    formData: { user: 'test' },
                    success(res) {
                        let data = JSON.parse(res.data)
                        if (data.code == 0) {
                            tmp.info.icon = data.data
                        }else{
                            wx.showToast({
                                title: '上传失败',
                                icon: 'none',
                                duration: 2000
                            })
                        }
                    },
                    fail() {
                        wx.showToast({
                            title: '上传失败',
                            icon: 'none',
                            duration: 2000
                        })
                    }
                });
            },
 
 
        }
    };
</script>
<style lang="less" scoped>
    @import url('./personalInfo.less');
    @import url('@/commin/flex.less');
 
 
    .chooseavatar {}
 
    .chooseavatar::after {
        border: none;
    }
	/deep/ .placeholder{
		color:grey;
		font-size:28rpx;
	}
	.listVal1{
		max-width:400rpx;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
    
</style>